package marketeer;

import general.MarketPlaceMarketeerInterface;

import java.rmi.RMISecurityManager;
import java.util.Iterator;
import java.util.LinkedList;

import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.discovery.LookupDiscovery;
import net.jini.discovery.LookupDiscoveryManager;
import net.jini.lease.LeaseRenewalManager;
import net.jini.lookup.LookupCache;
import net.jini.lookup.ServiceDiscoveryEvent;
import net.jini.lookup.ServiceDiscoveryListener;
import net.jini.lookup.ServiceDiscoveryManager;

public class MarketPlaceMonitor implements ServiceDiscoveryListener { 
	
	private LookupCache fMarketPlaceCache;

	public MarketPlaceMonitor() { 
		
		// Install security manager
		System.setProperty("java.security.policy", "config/marketeer.policy");
		System.setSecurityManager(new RMISecurityManager());
		
		// Construct MarketPlace cache
		ServiceDiscoveryManager clientMgr = null; 
	
		try {
			LookupDiscoveryManager mgr = new LookupDiscoveryManager(LookupDiscovery.ALL_GROUPS, null, null); 
			clientMgr = new ServiceDiscoveryManager(mgr, new LeaseRenewalManager());
		} catch (Exception e) { 
			e.printStackTrace();
		}
		
		Class[] classes = new Class[] { MarketPlaceMarketeerInterface.class };
		ServiceTemplate template = new ServiceTemplate(null, classes, null);
		try {
			fMarketPlaceCache = clientMgr.createLookupCache(template, null, this);
		} catch (Exception e) { 
			e.printStackTrace();
		}
	}
	
	public Iterator<MarketPlaceMarketeerInterface> getMarketPlaces() {
		LinkedList<MarketPlaceMarketeerInterface> resultList = new LinkedList<MarketPlaceMarketeerInterface>();
		ServiceItem[] services = fMarketPlaceCache.lookup(null, 100);
		for (int i = 0; i < services.length; i++) {
			resultList.add( (MarketPlaceMarketeerInterface) services[i].service);
		}
		return resultList.iterator();
	}
	
	public MarketPlaceMarketeerInterface getRandomMarketPlace() {
		ServiceItem[] services = fMarketPlaceCache.lookup(null, 100);
		return (MarketPlaceMarketeerInterface) services[(int) (Math.random() * (services.length))].service;
	}
 
	@Override
	public void serviceAdded(ServiceDiscoveryEvent arg0) {
		System.out.println("Service added");
		
	}

	@Override
	public void serviceChanged(ServiceDiscoveryEvent arg0) {
		System.out.println("Service changed");
		
	}

	@Override
	public void serviceRemoved(ServiceDiscoveryEvent arg0) {
		System.out.println("Service removed");
	}
}
